package com.mes.handler;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.openbravo.client.application.process.BaseProcessActionHandler;
import org.openbravo.dal.service.OBDal;
import com.mes.data.EmesCalendarTemplate;
import com.mes.data.EmesCalendarTemplateTime;
import com.mes.data.EmesShopCalendar;
import com.mes.data.EmesShopCalendarDate;
import com.mes.data.EmesShopCalendarTime;

public class ShopCalendarTemplateHandler extends BaseProcessActionHandler {
	private static final Logger logger = Logger.getLogger(ShopCalendarTemplateHandler.class);
	private String[] weekday = new String[]{"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
	public static SimpleDateFormat GET_DATE_YMD = new SimpleDateFormat("yyyy-MM-dd");
	public static SimpleDateFormat GET_DATE_SFM = new SimpleDateFormat("hh:mm:ss");
	
	@Override
	protected JSONObject doExecute(Map<String, Object> parameters, String content) {
		JSONObject responseResult = new JSONObject();
		JSONObject message = new JSONObject();
		try {
			responseResult.put("message", message);
			JSONObject request = new JSONObject(content);
			JSONArray selection = request.getJSONObject("_params").getJSONObject("MESCalendarTemplate").getJSONArray(
					"_selection");
			if (selection.length() == 0) {// 请选择记录
				responseResult.put("retryExecution", true);
				message.put("severity", "error");
				message.put("text", "请选择一项工作模板用来生成工厂日历");
				return responseResult;
			} else {
				// 获取参数
				String shopCalendarId = request.getString("inpemesShopCalendarId");
				String start_date = request.getJSONObject("_params").getString("Emes_sss");
				String end_date = request.getJSONObject("_params").getString("Emes_eee");
				JSONArray calendarTemplate = request.getJSONObject("_params").getJSONObject("MESCalendarTemplate")
						.getJSONArray("_selection");
				String calendarTemplateId = calendarTemplate.getJSONObject(0).getString("id");
				// 判断时间为空
				if (start_date == null || "null".equalsIgnoreCase(start_date) || end_date == null
						|| "null".equalsIgnoreCase(end_date)) {
					responseResult.put("retryExecution", true);
					message.put("severity", "error");
					message.put("text", "您输入的时间有误，请仔细检查。");
					return responseResult;
				}
				// 处理时间
				Date stratDate = null;
				Date endDate = null;
				try {
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					stratDate = sdf.parse(start_date);// 开始时间
					endDate = sdf.parse(end_date);// 结束时间
				} catch (ParseException e) {
					responseResult.put("retryExecution", true);
					message.put("severity", "error");
					message.put("text", "系统繁忙，请稍后再试。");
					return responseResult;
				}
				// 判断时间是否正确
				if (stratDate.after(endDate)) {
					responseResult.put("retryExecution", true);
					message.put("severity", "error");
					message.put("text", "您输入的时间有误，请仔细检查。");
					return responseResult;
				}
				calendarTemplateFactory(shopCalendarId, calendarTemplateId, stratDate, endDate);
				OBDal.getInstance().commitAndClose();
			}
		} catch (JSONException e) {
			try {
				responseResult.put("retryExecution", true);
				message.put("severity", "error");
				message.put("text", "系统繁忙，请稍后再试。");
				OBDal.getInstance().rollbackAndClose();
				return responseResult;
			} catch (JSONException e1) {
				logger.error(e1);
			}
			logger.error(e);
		}
		return new JSONObject();
	}
	
	protected JSONObject calendarTemplateFactory(String shopcalendarId, String calendarTemplateId, Date start_Date,
			Date end_Date) {
		JSONObject result = new JSONObject();
		JSONObject message = new JSONObject();
		// 日历信息ID
		EmesShopCalendar shopCalendar = OBDal.getInstance().get(EmesShopCalendar.class, shopcalendarId);
		// 日历模板信息ID
		EmesCalendarTemplate template = OBDal.getInstance().get(EmesCalendarTemplate.class, calendarTemplateId);
		// 日历模板下所有记录
		List<EmesCalendarTemplateTime> timeList = template.getEmesCalendarTemplateTimeList();
		// 该日历模板下所有有记录的
		List<EmesShopCalendarDate> dateList = shopCalendar.getEmesShopCalendarDateList();
		// 取出所有时间用于判断工作天是否可重复插入
		Map<Date, List> dateInDateMap = new HashMap<Date, List>();
		// 存储EmesShopCalendarDate，用于更新
		Map<Date, EmesShopCalendarDate> dateMap = new HashMap<Date, EmesShopCalendarDate>();
		Boolean timesFlag = dateList.isEmpty();
		if (timesFlag) {
		} else {
			for (EmesShopCalendarDate dateIndex : dateList) {
				dateInDateMap.put(dateIndex.getCalendarDate(), dateIndex.getEmesShopCalendarTimeList());
				dateMap.put(dateIndex.getCalendarDate(), dateIndex);
			}
		}
		Calendar calendar_start = new GregorianCalendar();
		Calendar calendar_end = new GregorianCalendar();
		calendar_start.setTime(start_Date);
		calendar_end.setTime(end_Date);
		// calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
		// date=calendar.getTime(); //这个时间就是日期往后推一天的结果
		EmesShopCalendarTime t = null;
		calendar_end.add(Calendar.DATE, 1);
		while (!DateUtils.isSameDay(calendar_start, calendar_end)) {
			if (dateList.isEmpty()) {
				// 如果为空，则创建当天的日历
				EmesShopCalendarDate emesShopCalendarDate = new EmesShopCalendarDate();
				emesShopCalendarDate.setCalendarDate(calendar_start.getTime());
				// 获取月份
				int month = calendar_start.get(Calendar.MONTH) + 1;
				calendar_start.add(Calendar.DATE, -1);
				// 获取一年中的第几周
				int week = calendar_start.get(Calendar.WEEK_OF_YEAR);
				calendar_start.add(Calendar.DATE, 1);
				emesShopCalendarDate.setMonth(month + "月份");
				emesShopCalendarDate.setWeekday(weekday[(calendar_start.get(Calendar.DAY_OF_WEEK) - 1)]);
				emesShopCalendarDate.setWeek("第" + week + "周");
				// 存储工作日
				emesShopCalendarDate.setEmesShopCalendar(shopCalendar);
				OBDal.getInstance().save(emesShopCalendarDate);
				for (EmesCalendarTemplateTime time : timeList) {
					// 储星期几的工作时间和工作效率
					if (String.valueOf(calendar_start.get(Calendar.DAY_OF_WEEK) - 1).equalsIgnoreCase(
							time.getWeekday())) {
						t = new EmesShopCalendarTime();
						// 判断是否是工作日
						if (String.valueOf(calendar_start.get(Calendar.DAY_OF_WEEK) - 1).equalsIgnoreCase(
								time.getWeekday())) {
							if (time.getWorkEfficiency() != null) {
								emesShopCalendarDate.setWorkday(true);
							}
						}
						t.setTimeFrom(DateToTimeStap(emesShopCalendarDate.getCalendarDate(), time.getTimeFrom()));
						t.setTimeTo(DateToTimeStap(emesShopCalendarDate.getCalendarDate(), time.getTimeTo()));
						t.setTimeFrom(time.getTimeFrom());
						t.setTimeTo(time.getTimeTo());
						t.setWorkEfficiency(time.getWorkEfficiency());
						t.setEmesShopCalendarDate(emesShopCalendarDate);
						OBDal.getInstance().save(t);
					}
					;
				}
			} else {
				if (dateInDateMap.containsKey(calendar_start.getTime())) {
					// 如果包含已经创建的时间，则不生成当天的日历，保存原有的日历
					if (dateInDateMap.get(calendar_start.getTime()).isEmpty()) {
						// 如果为空，则创建当天的日历
						EmesShopCalendarDate emesShopCalendarDate = dateMap.get(calendar_start.getTime());
						// 更新
						for (EmesCalendarTemplateTime time : timeList) {
							// 储星期几的工作时间和工作效率
							if (String.valueOf(calendar_start.get(Calendar.DAY_OF_WEEK) - 1).equalsIgnoreCase(
									time.getWeekday())) {
								t = new EmesShopCalendarTime();
								// 判断是否是工作日
								if (String.valueOf(calendar_start.get(Calendar.DAY_OF_WEEK) - 1).equalsIgnoreCase(
										time.getWeekday())) {
									if (time.getWorkEfficiency() != null) {
										emesShopCalendarDate.setWorkday(true);
									}
								}
								t.setTimeFrom(DateToTimeStap(emesShopCalendarDate.getCalendarDate(), time
										.getTimeFrom()));
								t
										.setTimeTo(DateToTimeStap(emesShopCalendarDate.getCalendarDate(), time
												.getTimeTo()));
								t.setWorkEfficiency(time.getWorkEfficiency());
								t.setEmesShopCalendarDate(emesShopCalendarDate);
								OBDal.getInstance().save(t);
							}
							;
						}
					}
				} else {
					// 如果为空，则创建当天的日历
					EmesShopCalendarDate emesShopCalendarDate = new EmesShopCalendarDate();
					emesShopCalendarDate.setCalendarDate(calendar_start.getTime());
					// 获取月份
					int month = calendar_start.get(Calendar.MONTH) + 1;
					calendar_start.add(Calendar.DATE, -1);
					// 获取一年中的第几周
					int week = calendar_start.get(Calendar.WEEK_OF_YEAR);
					calendar_start.add(Calendar.DATE, 1);
					emesShopCalendarDate.setMonth(month + "月份");
					emesShopCalendarDate.setWeekday(weekday[(calendar_start.get(Calendar.DAY_OF_WEEK) - 1)]);
					emesShopCalendarDate.setWeek("第" + week + "周");
					// 判断是否是工作日
					// 存储工作日
					emesShopCalendarDate.setEmesShopCalendar(shopCalendar);
					OBDal.getInstance().save(emesShopCalendarDate);
					for (EmesCalendarTemplateTime time : timeList) {
						// 储星期几的工作时间和工作效率
						if (String.valueOf(calendar_start.get(Calendar.DAY_OF_WEEK) - 1).equalsIgnoreCase(
								time.getWeekday())) {
							t = new EmesShopCalendarTime();
							if (String.valueOf(calendar_start.get(Calendar.DAY_OF_WEEK) - 1).equalsIgnoreCase(
									time.getWeekday())) {
								if (time.getWorkEfficiency() != null) {
									emesShopCalendarDate.setWorkday(true);
								}
							}
							t
									.setTimeFrom(DateToTimeStap(emesShopCalendarDate.getCalendarDate(), time
											.getTimeFrom()));
							t.setTimeTo(DateToTimeStap(emesShopCalendarDate.getCalendarDate(), time.getTimeTo()));
							t.setWorkEfficiency(time.getWorkEfficiency());
							t.setEmesShopCalendarDate(emesShopCalendarDate);
							OBDal.getInstance().save(t);
						}
						;
					}
				}
			}
			calendar_start.add(Calendar.DATE, 1);
		}
		// return result;
		result.remove("message");
		return result;
	}
	
	/**
	 * 时间处理工具
	 * @param date
	 * @param stamp
	 * @return
	 */
	public static Timestamp DateToTimeStap(Date date, Timestamp stamp) {
		String str = stamp.toString();
		String str1 = GET_DATE_YMD.format(date);
		str = str1 + str.substring(10, str.length());
		return Timestamp.valueOf(str);
	}
}
